package com.zzzy.sys.controller;

import com.zzzy.sys.dao.entity.Dept;
import com.zzzy.sys.service.DeptService;
import com.zzzy.sys.vo.dept.DeptAddReq;
import com.zzzy.sys.vo.dept.DeptListReq;
import com.zzzy.sys.vo.dept.DeptTreeVO;
import com.zzzy.sys.vo.dept.DeptUpdateReq;
import com.zzzy.common.vo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@Tag(name = "部门管理", description = "sys002")
@Validated
@RestController
@RequestMapping("/system/dept")
public class DeptController {

    @Resource
    private DeptService deptService;

    @Operation(summary = "部门列表")
    @GetMapping(value = "/list")
    @PreAuthorize("@pvs.hasPermission('system:dept:list')")
    public AjaxResult<List<Dept>> list(@Valid @ParameterObject DeptListReq queryReq) {
        List<Dept> deptList = deptService.getDeptList(queryReq);
        return AjaxResult.success(deptList);
    }

    @Operation(summary = "部门列表树形结构")
    @GetMapping(value = "/tree")
    @PreAuthorize("@pvs.hasPermission('system:dept:list')")
    public AjaxResult<List<DeptTreeVO>> tree() {
        List<DeptTreeVO> deptList = deptService.getDeptTree();
        return AjaxResult.success(deptList);
    }

    @PostMapping("/add")
    @Operation(summary = "新增部门")
    @PreAuthorize("@pvs.hasPermission('system:dept:add')")
    public AjaxResult add(@Valid @RequestBody DeptAddReq addReq) {
        deptService.addDept(addReq);

        return AjaxResult.success();
    }

    @GetMapping(value = {"/getDept/{id}"})
    @Operation(summary = "获得部门")
    @Parameter(name = "id", description = "部门ID", required = true)
    @PreAuthorize("@pvs.hasPermission('system:dept:list')")
    public AjaxResult<Dept> getDept(@NotNull(message = "部门ID不能为空") @PathVariable("id") Long id) {
        Dept dept = deptService.getDeptById(id);
        return AjaxResult.success(dept);
    }

    @PutMapping("/update")
    @Operation(summary = "修改部门")
    @PreAuthorize("@pvs.hasPermission('system:dept:update')")
    public AjaxResult update(@Valid @RequestBody DeptUpdateReq updateReq) {
        deptService.updateById(updateReq);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除部门")
    @Parameter(name = "id", description = "部门ID", required = true)
    @PreAuthorize("@pvs.hasPermission('system:dept:delete')")
    public AjaxResult delete(@NotNull(message = "部门ID不能为空") @PathVariable("id") Long id) {
        deptService.deleteById(id);
        return AjaxResult.success();
    }
}
